package com.h3bpm.web.controller;

import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Controller.RestfulApi.cloudpivot.ResponseResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.web.utils.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 *  erp 数据 定时写到bpm 中
 */
@RestController
@RequestMapping("/api/erp")
public class ErpDataCotnroller  extends ControllerBase {

    @Value("${erpVendorUrl:http://10.50.132.90:8001/vendor}")
    private String erpVendorUrl;

    private static final Logger log = LoggerFactory.getLogger(ErpDataCotnroller.class);

    /**
     * 手动更新erp
     * @return
     */
    @RequestMapping("/updateErpCounterparty")
    public ResponseResult updateErpCounterparty(){


       return getErpCounterparty();
    }

    /**
     * 定时任务 ,早上8 点到 下午6 点 每30 分钟触发一次
     */
//    @Scheduled(cron = "0 0/30 8-18 * * ?")
//    public void ErpCounterPartyTimeTask(){
//        if (log.isDebugEnabled()) {
//
//            log.info("相对方定时任务开始...");
//        }
//
//        getErpCounterparty();
//
//    }


    /**
     *  相对方信息从erp 写到 bpm 数据库
     */
    private ResponseResult  getErpCounterparty(){
        ResponseResult result = new ResponseResult(-1L,"",null);
        String sql = "SELECT count(1) as count from erp_counterparty  ";

        int count = getEngine().getPortalQuery().count(sql);

        try {

            String rst = HttpClientUtils.doGet(erpVendorUrl);

            if (rst != null) {

                JSONObject jsonObject = JSON.parseObject(rst);

                Integer total = Optional.ofNullable(jsonObject.getInteger("total")).orElse(0);

                log.info("total = {}",total);

                if (total > 0 && total > count) {

                    JSONArray list = jsonObject.getJSONArray("rows");

                    StringBuilder instSql = new StringBuilder("INSERT INTO  erp_counterparty (  vendorName, vendorCode, validFlag, freezeFlag) VALUES ");

                    JSONObject vendor ;
                    for (int i = count; i < total; i++) {
                        vendor = (JSONObject) list.get(i);

                        instSql.append("('")
                            .append(vendor.getString("vendorName")).append("','")
                            .append(vendor.getString("vendorCode")).append("','")
                            .append(vendor.getString("validFlag")).append("','")
                            .append(vendor.getString("freezeFlag")).append("'),");
                    }

                    instSql.deleteCharAt(instSql.length()-1);


                    int i = getEngine().getPortalQuery().ExcuteNoQuery(instSql.toString());

                    log.info("插入数据 [{}]", i);
                    result.setErrmsg("更新成功 int=".concat(String.valueOf(i)));

                }else{
                    result.setErrmsg("没有最新数据");
                }
                result.setErrcode(0l);


            }else{
                result.setErrmsg("rst is null");
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setErrmsg("系统异常");
        }

        return  result;


    }


    @Override
    public String getFunctionCode() {
        return null;
    }
}
